﻿using MaterialTypeRecognition.Shell.SaveInfoService;
using System.IO;
using System.Threading.Tasks;

namespace WebMiddleware.SaveInfoService
{
    internal class TypeSaveInfoService : ISaveInfoService
    {
        private readonly IStore<Stream> _store;

        public TypeSaveInfoService(IStore<Stream> store)
        {
            _store = store;
        }

        public TModel Read<TModel>() where TModel : class, new()
        {
            return _store.Rent(JsonConfigFileHelper.Read<TModel>);
        }

        public Task<TModel> ReadAsync<TModel>() where TModel : class, new()
        {
            return _store.RentAsync(JsonConfigFileHelper.Read<TModel>);
        }

        public void Write<TModel>(TModel model) where TModel : class, new()
        {
            _store.Rent<TModel>(stream =>
            {
                JsonConfigFileHelper.Write(stream, model);
            });
        }

        public Task WriteAsync<TModel>(TModel model) where TModel : class, new()
        {
            return _store.RentAsync<TModel>(stream =>
            {
                JsonConfigFileHelper.Write(stream, model);
            });
        }
    }
}
